﻿#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "os.h"

#if defined(WINDOWS)
#include "dirent_win.h"
#else
#include <dirent.h>
#endif

int test_read_file(char* url, char* buf, size_t* count)
{
	FILE* fd;
	size_t len;
	fd = pipe_open(url, "r"); 
	if (!fd) {
		return -1;
	}
	len = fread(buf, 1, *count, fd);
	pipe_close(fd);

	if (len == *count) {
		printf("file %s size is larger than %zu\n", url, *count);
		return -1;
	}
	*count = len;
	buf[len] = 0;
	//printf("%s\n",buf);
	return 0;
}


int get_website_from_url(char* url, char* web)
{
	int len;
	char* head;

	printf("url is %s\n", url);
	/* get website from url */
	head = strstr(url, "://");
	if (!head) {
		return -1;
	}
	head = head + strlen("://");
	head = strchr(head, '/');
	if (!head)
		return -1;
	len = (int)(head - url);
	strncpy( web, url, len);
	*(web + len) = 0;

	return 0;
}

/* read url content to file 
in:
	url: point to a link
	count: in, out, buffer length
	buf: user alloc 'count' bytes buffer
0 if read OK;
*/
int get_html_content(char* url, char* buf, size_t* count)
{
	char cmd[256];
	size_t len = *count;

	sprintf(cmd, "curl %s", url);

#if defined(WINDOWS)
	strcat(cmd, " 2> nul");
#elif defined(WIN32) //msys2
	//do nothing
#else
	strcat(cmd, " 2> /dev/null");
#endif
	//printf("%s\n", cmd);
	if (test_read_file(cmd, buf, &len)) {
		return -1;
	}

	*count = len;
	return 0;
}

// Check if the file exists
int FileExists(const char *fileName)
{
    int result = 0;

#if defined(WINDOWS)
    if (_access(fileName, 0) != -1) result = 1;
#else
    if (access(fileName, F_OK) != -1) result = 1;
#endif

    // NOTE: Alternatively, stat() can be used instead of access()
    //#include <sys/stat.h>
    //struct stat statbuf;
    //if (stat(filename, &statbuf) == 0) result = 1;

    return result;
}

// Check if a directory path exists
int DirectoryExists(const char* dirPath)
{
	int result = 0;
	DIR* dir = opendir(dirPath);

	if (dir != NULL)
	{
		result = 1;
		closedir(dir);
	}

	return result;
}


